// web/src/app/learn/(course)/courses/[courseId]/chapters/[chapterId]/_components/video-player.tsx
'use client';
import React, {useState} from 'react';
import {Loader2, Lock} from "lucide-react";
import {cn} from "@/lib/utils";
import Player from 'next-video/player';
import Video from 'next-video';
import MediaThemeHalloween from 'player.style/halloween/react';
import {useRouter} from "next/navigation";
import {useConfettiStore} from "@/hooks/learn/use-confetti-store";
import toast from "react-hot-toast";

// import Instaplay from 'player.style/instaplay/react';

interface Props {
    // playbackId?: string
    videoUrl?: string
    courseId: string
    chapterId: string
    nextChapterId: string
    isLocked: boolean
    completeOnEnd: boolean
    title: string
}

const VideoPlayer = ({
                         videoUrl, courseId, chapterId, completeOnEnd, title, isLocked, nextChapterId
                     }: Props) => {
    const [isReady, setIsReady] = useState(false)
    const router = useRouter()
    const confetti = useConfettiStore()

    // 视频播放结束 更新章节完成 跳转下一章
    const onEnd = async () => {
        try {
            if (completeOnEnd) {
                const res = await fetch(`/api/course/${courseId}/chapters/${chapterId}/progress`, {
                    method: "PUT",
                    headers: {
                        "Content-Type": "application/json",
                    },
                    body: JSON.stringify({isCompleted: true})
                })
                if (!res.ok) throw new Error(`Failed to fetch`)

                if (!nextChapterId) {
                    confetti.onOpen()
                }

                toast.success(`Progress updated`)
                router.refresh()

                if (nextChapterId) {
                    router.push(`/learn/courses/${courseId}/chapters/${nextChapterId}`)
                }
            }

        } catch (e) {
            console.error(e)
            toast.error(`Something went wrong`)
        }
    }

    return (
        <div className={`relative aspect-video`}>
            {!isLocked && !isReady && (
                <div className={`absolute inset-0 flex items-center justify-center bg-slate-800`}>
                    <Loader2 className={`size-8 animate-spin text-secondary`}/>
                </div>
            )}
            {isLocked && (
                <div className={`absolute inset-0 flex items-center justify-center bg-slate-800
                flex-col gap-y-2 text-secondary`}>
                    <Lock className={`size-8`}/>
                    <p className={`text-sm`}>
                        This chapter is locked
                    </p>
                </div>
            )}
            {!isLocked && (
                // <video
                //     src={videoUrl}
                //     controls
                //     title={title}
                //     className={cn(
                //         !isReady && 'hidden'
                //     )}
                //     onCanPlay={() => setIsReady(true)}
                //     onEnded={() => {
                //     }}
                //     autoPlay
                //     // playbackId={}
                // />
                // <Player
                <Video
                    // src={playbackId ? undefined : `http://localhost:3000${videoUrl}`}
                    src={`${process.env.NEXT_PUBLIC_APP_URL}${videoUrl}`}
                    // poster （StaticImageData | string）：视频的占位符图像。 （为 Mux 视频自动生成）
                    // blurDataURL (string): A base64 image source URL that can be used as a placeholder. (Auto generated for Mux videos)
                    // blurDataURL （字符串）：可用作占位符的 Base64 图像源 URL。 （为 Mux 视频自动生成）
                    // poster="https://www.mydomain.com/remote-poster.webp"
                    // poster="/video-cover-5.jpg"
                    // blurDataURL="..."
                    controls
                    // accentColor={'blue'}
                    // theme={MediaThemeHalloween}
                    title={title}
                    className={cn(
                        !isReady && 'hidden'
                    )}
                    onCanPlay={() => {
                        setIsReady(true)
                    }}
                    onEnded={onEnd}
                    // playbackId={playbackId || undefined}
                    autoPlay
                />
            )}
        </div>
    );
};

export default VideoPlayer;